<template>
  <div
    v-loading="loading"
    v-init-screen-h="10"
    class="camera_box w100"
    element-loading-text="摄像头加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(3,10,70, 0.8)"
  >
    <dv-border-box-12 ref="box12ref1" class="right_content">
      <CheckboxList
        :showStreamIcon="true"
        :iWind="iWind"
        @handleCommand="handleCommand"
        :codeStreamList="codeStreamList"
        :checkList="checkList"
        @onDbChangeCheck="onChangeCheck"
      ></CheckboxList>
    </dv-border-box-12>
    <dv-border-box-12 ref="box12ref2" class="play_content">
      <div id="playWind" class="w100"></div>
      <VideoToolbar
        v-if="checkList.length"
        @previousPage="previousPage"
        @nextPage="nextPage"
        :currentVideo="currentVideo"
        @handleCamera="handleCamera"
        @setVolumeAll="setVolumeAll"
        @changeSound="changeSound"
        :isPlay="isPlay"
        @playOrStopAll="playOrStopAll"
        @fullScreen="fullScreen"
        @arrangeWindow="arrangeWindow"
      ></VideoToolbar>
      <!-- <div class="timeline" v-if="cameraFlag === '2'">
        <TimeLine
          ref="Timeline2"
          :initTime="time2"
          @timeChange="timeChange2"
          :timeSegments="timeSegments"
          @click_timeSegments="click_timeSegments"
          @click_timeline="onClickTimeLine"
          @dragTimeChange="onDragTimeChange"
        ></TimeLine>
      </div> -->
    </dv-border-box-12>
  </div>
</template>

<script>
import _ from "lodash";
import CheckboxList from "./components/CheckboxList.vue";
import VideoToolbar from "./components/VideoToolbar.vue";
import TimeLine from "@/components/TimeLine";
import moment from "moment";
import axios from "axios";
// const HOST = document.location.host;
// const USERNAME_PASSWORD = "admin:hk12345678";
// const VIDEO_BAER_URL = `http://${USERNAME_PASSWORD}@${HOST}/ISAPI`;
// // const DEV_INDEX = "17031824-26B8-184D-84B5-161937A2C988";
// const ACCESS_URL = "ws://" + process.env.VUE_APP_CAMEAR_URL;
// const RTSP_URL = "192.168.11.204:554";
import {
  CAMERA_LIST,
  CODE_STREAM,
  USERNAME_PASSWORD,
  VIDEO_BAER_URL,
  ACCESS_URL
} from "./constent";
export default {
  components: {
    CheckboxList,
    VideoToolbar,
    TimeLine
  },
  computed: {
    // 当前分页的数组
    getPagesArr() {
      // 根据当前的宫格数量 拿到能够分几页
      const numbers = parseInt(
        this.checkList.length / this.playAllWindowNumber
      );
      let arr = [];
      // 取出余数,相当于最后一页能放几个
      const surplus = this.checkList.length % this.playAllWindowNumber;
      for (let i = 0; i < numbers; i++) {
        arr.push(this.playAllWindowNumber);
      }
      // 如果最后一页不能放满,就单独加进去
      if (surplus !== 0) {
        arr.push(surplus);
      }
      let list = [];
      let n = 0;
      const deepData = _.cloneDeep(this.checkList);
      arr.forEach((item, i) => {
        list.push([deepData.splice(0, item)]);
        n = n + item;
      });
      return list;
    },
    // 当前播放的视频数量
    playAllWindowNumber() {
      return this.windowNumber * this.windowNumber;
    },
    // 是否有视频正在播放
    isPlay() {
      return this.checkList.every(item => item.iWind == -1);
    },
    // 当前选中的视频
    currentVideo() {
      return this.checkList.find(item => item.iWind == this.iWind);
    },
    // 最后一页
    lastPage() {
      return Math.floor(this.checkList.length / this.playAllWindowNumber);
    },
    // 当前窗口有几个视频正在播放
    playNumber() {
      return this.checkList.filter(item => item.iWind !== -1).length;
    }
  },
  data() {
    return {
      loading: false,
      jsDecoder: null,
      iWind: 0,
      VideoInputChannelList: [],
      checkList: [],
      codeStreamList: CODE_STREAM,
      windowNumber: 3,
      pageNumber: -1,
      devIndex: "17031824-26B8-184D-84B5-161937A2C988",
      time2: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
      timer: null,
      timeSegments: [
        {
          name: "时间段1",
          beginTime: new Date("2023-02-04 10:00:00").getTime(),
          endTime: new Date("2023-02-04 23:00:00").getTime(),
          color: "#FA3239",
          startRatio: 0.75,
          endRatio: 1
        },
        {
          name: "时间段2",
          beginTime: new Date("2023-02-05 02:00:00").getTime(),
          endTime: new Date("2023-02-05 18:00:00").getTime(),
          color: "#836ABB",
          startRatio: 0.75,
          endRatio: 1
        }
      ]
    };
  },
  watch: {
    cameraFlag: {
      handler: function() {
        if (this.cameraFlag == "预览") {
          console.log("1 :>> ", 1);
          setTimeout(() => {
            this.init();
          }, 500);
        }
      },
      immediate: true
    },
    // 有bug 晚点改
    "$store.state.app.sidebar.opened"() {
      setTimeout(() => {
        if (this.$refs.box12ref1) {
          this.$refs.box12ref1.initWH();
          this.$refs.box12ref2.initWH();
          // 从新设置容器的宽高
          this.resizeWH();
        }
      }, 500);
    }
  },
  destroyed() {
    window.removeEventListener("resize", this.resizeWH);
  },
  async mounted() {},
  //时间轴
  beforeDestroy() {
    this.stopRealPlayAll();
    clearTimeout(this.timer);
  },
  props: {
    cameraFlag: {
      type: String,
      default: ""
    }
  },
  methods: {
    async init() {
      // 此处解决 双击放大之后 无法全屏的问题
      try {
        this.loading = true;
        this.devIndex = await this.getDevIndex();
        this.checkList = await this.getVideoList();
        this.loading = false;
        window.addEventListener("resize", this.resizeWH);
        this.$nextTick(() => {
          // 初始化容器
          this.rendererPlay();
          // 初始化监听函数
          this.initPlugin();
        });
      } catch (error) {
        this.$msg("摄像头获取失败");
        this.loading = false;
      }
      // this.checkList = CAMERA_LIST.map(item => {
      //   return {
      //     VideoInputChannel: {
      //       ...item.VideoInputChannel
      //     },
      //     isCheck: false, //单击选中
      //     iWind: -1, //当前播放的窗口
      //     codeStreamValue: CODE_STREAM[1].value,
      //     isVolume: false //是否开启声音
      //   };
      // });
    },
    // 时间轴
    timeChange2(t) {
      this.time2 = t;
    },
    click_timeSegments(arr) {
      console.log("onClickTimeSegments", arr);
      alert("点击了：" + arr[0].name);
    },
    onClickTimeLine(...args) {
      console.log("onClickTimeLine", args);
    },
    onDragTimeChange(...args) {
      console.log("onDragTimeChange", args);
    },
    checkFlag(e) {
      console.log(this.time2);
      if (e === "2") {
        this.time2 = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
        this.timer = setInterval(() => {
          this.time2 += 1000;
          this.$refs.Timeline2.setTime(this.time2);
        }, 1000);
      } else {
        clearTimeout(this.timer);
      }
    },
    // 获取录像机id
    getDevIndex() {
      return new Promise((reslove, reject) => {
        axios({
          method: "post",
          url: `${VIDEO_BAER_URL}/ContentMgmt/DeviceMgmt/deviceList?format=json`,
          data: {
            SearchDescription: {
              position: 0,
              maxResult: 100,
              Filter: {
                key: "",
                devType: "",
                protocolType: ["ehomeV5"],
                devStatus: ["online", "offline"]
              }
            }
          }
        })
          .then(res => {
            if (res.data.SearchResult.MatchList.length) {
              const devIndex =
                res.data.SearchResult.MatchList[0].Device.devIndex;
              reslove(devIndex);
            } else {
              reject();
            }
          })
          .catch(err => {
            reject();
          });
      });
    }, // 拍照
    handleCamera() {
      if (this.currentVideo) {
        this.jsDecoder.JS_CapturePicture(
          this.iWind,
          this.currentVideo.VideoInputChannel.name,
          "jpg"
        );
      }
    },
    // 关闭所有声音
    closeSoundAll() {
      this.checkList.forEach(item => {
        item.isVolume = false;
        if (item.iWind !== -1) {
          this.closeSound(item.iWind);
        }
      });
    },
    // 一键开始/关闭声音
    setVolumeAll(val) {
      // 开启之前先关闭其他的声音
      this.checkList.forEach(item => {
        if (item.iWind == this.iWind) {
          item.isVolume = item.isVolume ? false : true;
          if (item.isVolume) {
            this.openSound();
          } else {
            this.closeSound(item.iWind);
          }
        } else if (item.iWidth !== -1) {
          item.isVolume = false;
        } else {
          item.isVolume = false;
          this.closeSound(item.iWind);
        }
      });
    },
    // 声音进度条
    async changeSound(val) {
      if (!val) {
        this.closeSound(this.iWind);
      } else {
        this.$msg(val + "");
        await this.jsDecoder.JS_SetVolume(this.iWind, val);
        this.openSound();
        this.JS_GetVolume();
      }
    },
    // 设置音量大小
    JS_SetVolume(iVolume) {
      this.jsDecoder.JS_SetVolume(this.iWind, iVolume);
    },
    // 获取音量大小
    async JS_GetVolume(iVolume) {
      const a = await this.jsDecoder.JS_GetVolume(this.iWind);
      console.log(a);
    },
    // 控制声音和大小开关
    openSound() {
      this.jsDecoder.JS_OpenSound(this.iWind);
    },
    closeSound(iWind) {
      this.jsDecoder.JS_CloseSound(iWind);
    },
    //还原数组的播放状态
    initList() {
      this.checkList.forEach(item => {
        item.iWind = -1;
      });
    },
    // 关闭全部
    stopRealPlayAll() {
      this.initList();
      if (this.jsDecoder) {
        this.jsDecoder.JS_StopRealPlayAll();
      }
    },
    destroyWorker() {
      this.jsDecoder.JS_DestroyWorker();
    },
    // 下一页
    nextPage() {
      // 先判断当前窗口是否 全部已被占用,全部占用则直接下一页,否则从0开始
      // if (this.playNumber == this.playAllWindowNumber) {

      // } else {
      //   // 播放之前先暂停全部
      //   this.playAll();
      // }
      this.stopRealPlayAll();
      this.pageNumber = this.pageNumber + 1;
      // 如果是最后一页 就返回到第一页
      if (this.pageNumber == this.getPagesArr.length) {
        this.pageNumber = 0;
      }
      this.$msg("当前在第几页:" + this.pageNumber);
      // 当前页码的数组
      const arr = this.getPagesArr[this.pageNumber][0];
      for (let i = 0; i < arr.length; i++) {
        this.onChangeCheck(arr[i], i);
      }
    },
    // 上一页
    previousPage() {
      this.stopRealPlayAll();
      this.pageNumber = this.pageNumber - 1;
      this.$msg("当前在第几页:" + this.pageNumber);
      // 如果是第一页 就跳转到最后一页
      if (this.pageNumber == -2 || this.pageNumber == -1) {
        this.pageNumber = this.getPagesArr.length - 1;
      }
      const arr = this.getPagesArr[this.pageNumber][0];
      for (let i = 0; i < arr.length; i++) {
        this.onChangeCheck(arr[i], i);
      }
    },
    // 全部开始播放(根据当前宫格数量)
    playAll() {
      for (let i = 0; i < this.playAllWindowNumber; i++) {
        this.onChangeCheck(this.checkList[i], i);
      }
    },
    // 播放/暂停全部
    playOrStopAll() {
      this.pageNumber = 0;
      // 停止所有播放
      if (!this.isPlay) {
        this.stopRealPlayAll();
      } else {
        // 播放之前先暂停全部
        this.stopRealPlayAll();
        this.playAll();
      }
    },
    // 获取摄像头列表
    getVideoList() {
      return new Promise((reslove, reject) => {
        axios({
          method: "get",
          url: `${VIDEO_BAER_URL}/System/Video/inputs/channels?format=json&devIndex=${this.devIndex}`
        })
          .then(res => {
            const list = res?.data?.VideoInputChannelList;
            const newList = list.map(item => {
              return {
                VideoInputChannel: {
                  ...item.VideoInputChannel
                },
                isCheck: false, //单击选中
                iWind: -1, //当前播放的窗口
                codeStreamValue: CODE_STREAM[1].value,
                isVolume: false //是否开启声音
              };
            });
            reslove(newList);
          })
          .catch(err => {
            reject();
          });
      });
    },
    // 全屏
    fullScreen() {
      this.fullSreen();
    },
    // 开始预览播放
    realplay(previewUrl, iWind) {
      console.log(
        "拿到地址准备播放 :>> ",
        USERNAME_PASSWORD,
        ACCESS_URL,
        iWind,
        previewUrl
      );
      const that = this;
      return new Promise((reslove, reject) => {
        this.jsDecoder
          .JS_Play(
            ACCESS_URL,
            {
              playURL: previewUrl, //play URL,
              auth: USERNAME_PASSWORD
            },
            iWind
          )
          .then(
            function() {
              console.log("播放成功");
              reslove(true);
            },
            function(err) {
              console.log("err :>> ", err);
              that.$msg("播放失败");
              reslove(false);
            }
          );
      });
    },
    // 获取播放的url
    getRtspUrl(videoId, codeStreamValue) {
      const str = codeStreamValue == "SUB" ? "sub" : "main";
      return new Promise((reslove, reject) => {
        axios({
          method: "post",
          url: `${VIDEO_BAER_URL}/System/streamMedia?format=json&devIndex=${this.devIndex}`,
          data: {
            StreamInfo: {
              id: videoId,
              streamType: str,
              method: "preview"
            }
          }
        })
          .then(res => {
            console.log("res :>> ", res);
            // reslove(
            //   `rtsp://${RTSP_URL}/dac/realplay/${this.devIndex}${videoId}/${codeStreamValue}/TCP?streamform=rtp`
            // );
            reslove(res.data.MediaAccessInfo.URL);
          })
          .catch(err => {
            this.$msg("播放地址获取失败");
          });
      });
    },
    // 重新设置窗口宽高
    resizeWH() {
      const { width, height } = this.getContentWH();
      if (this.jsDecoder) {
        this.jsDecoder.JS_Resize(width, height);
      }
    },
    // 获取容器宽高
    getContentWH() {
      const width = document.getElementById("playWind").offsetWidth - 5;
      const height = document.getElementById("playWind").offsetHeight;
      return {
        width,
        height
      };
    },
    // 初始化容器
    rendererPlay() {
      const { width, height } = this.getContentWH();
      this.jsDecoder = new JSPlugin({
        szId: "playWind",
        iWidth: width,
        iHeight: height,
        iMaxSplit: 4, //最大拆分
        iCurrentSplit: 3, //默认拆分
        szBasePath: "./jsPlugin",
        oStyle: {
          border: "#3B5F95",
          // box-shadow: 0 0 2px 2px rgba(71,167,235,.86);
          borderSelect: "#F7CE46",
          background: "rgba(58,58,89,.4)"
        },
        bOnlySupportJSDecoder: false
      });
    },
    // 宫格
    arrangeWindow(i) {
      this.pageNumber = 0;
      this.windowNumber = i;
      this.jsDecoder.JS_ArrangeWindow(i);
    },
    // 全屏
    fullSreen() {
      this.jsDecoder.JS_FullScreenDisplay(true);
    },
    // 单个全屏
    fullScreenSingle() {
      this.jsDecoder.JS_FullScreenSingle(this.iWind);
    },
    // 停止播放
    videoStop(iWind) {
      this.jsDecoder.JS_Stop(iWind);
    },
    // 选择码流
    async handleCommand(row, val) {
      row.codeStreamValue = val;
      // 设置码流之后 当前摄像头正在播放 从新播放
      if (row.iWind !== -1) {
        // 先停止播放
        this.videoStop(row.iWind);
        const id = row.VideoInputChannel.id;
        const codeStreamValue = row.codeStreamValue;
        // 获取rtsp播放地址
        const url = await this.getRtspUrl(id, codeStreamValue);
        // 开始播放
        this.realplay(url, row.iWind);
      }
    },

    // 选择播放的摄像头
    async onChangeCheck(rowObj, iWind) {
      const row = this.checkList.find(
        item => item.VideoInputChannel.id == rowObj.VideoInputChannel.id
      );
      let iw = iWind === undefined ? this.iWind : iWind;
      // 已经处于播放状态的 停止播放
      if (row.iWind !== -1) {
        this.videoStop(row.iWind);
        row.iWind = -1;
        return;
      }
      // 当前选择的播放框已存在播放的,就把已存在的停止播放
      this.checkList.forEach(item => {
        if (item.iWind == iw) {
          this.videoStop(item.iWind);
          item.iWind = -1;
        }
      });
      const id = row.VideoInputChannel.id;
      const codeStreamValue = row.codeStreamValue;
      // 获取rtsp播放地址
      const url = await this.getRtspUrl(id, codeStreamValue);
      // 开始播放
      const isSucc = await this.realplay(url, iw);
      // 播放成功
      if (isSucc) {
        row.iWind = iw;
      } else {
        row.iWind = -1;
      }
    },
    // 初始化
    initPlugin() {
      let that = this;
      this.jsDecoder.JS_SetWindowControlCallback({
        windowEventSelect: iWndIndex => {
          this.iWind = iWndIndex;
          this.$emit("updateIWind", iWndIndex);
        },
        pluginErrorHandler: function(iWndIndex, iErrorCode, oError) {
          console.log(iWndIndex, iErrorCode, oError);
          // 报错之后数组内部状态初始化
          that.checkList.forEach(item => {
            if (item.iWind == iWndIndex) {
              item.iWind = -1;
            }
          });
        },
        performanceLack: function() {
          console.log("性能不足");
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.camera_box {
  display: flex;
  .right_content {
    width: 20%;
    padding: 20px;
    /deep/ {
      .border-box-content {
        overflow: auto;
      }
      .border-box-content::-webkit-scrollbar-track {
        background-color: inherit;
        -webkit-border-radius: 0;
        -moz-border-radius: 0;
        border-radius: 0;
      }
      .border-box-content::-webkit-scrollbar-thumb {
        background-color: #5dcbff;
        -webkit-border-radius: 2em;
        -moz-border-radius: 2em;
        border-radius: 2em;
      }
      .border-box-content::-webkit-scrollbar {
        width: 4px !important;
      }
      .border-box-content::-webkit-scrollbar-corner {
        /* background-color: #5dcbff; */
        display: none;
      }
    }
  }
  .play_content {
    #playWind {
      // 高度 权重加到最高,不然会被行内的覆盖掉 导致高度出现计算不准确
      height: calc(100% - 35px) !important;
    }
    padding: 20px;
    width: 80%;
    height: 100%;
    // /deep/ .parent-wnd {
    //   display: flex;
    //   flex-wrap: wrap;
    // }
  }
  .timeline {
    height: 35px;
  }

  /deep/ .el-radio__label {
    color: #fff;
  }
  /deep/ .el-radio__input.is-checked + .el-radio__label {
    color: #409eff !important;
  }
}
</style>
